package com.study.webapp.jdk8;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @program: study
 *
 * @description:
 *
 * @author: heqiang
 *
 * @create: 2020-04-24 17:47
 **/
public class CyclicBarrierTest {


    private static final int NUMBER = 5;

    private static final Random random = new Random();

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(NUMBER, new Runnable() {
            @Override
            public void run() {
                System.out.println("全部执行完毕。。。。。。。");
            }
        });
        for (int i = 0; i<NUMBER; i++) {
            Thread t = new Thread(new MyRun("hahah"+i,cyclicBarrier));
            t.start();
        }
    }


    static class MyRun implements  Runnable {

        private CyclicBarrier cyclicBarrier;
        private String name;

        public MyRun (String name,CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
            this.name = name;
        }

        @Override
        public void run() {
            int time = random.nextInt(1000);
            System.out.println(name+"我需要："+time+"执行");
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name+"我执行好了，等待其他人");
            try {
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println(name+"全部等待好了。。。。");
        }
    }
}
